package com.etong.citymap.activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.etong.citymap.bean.AssignmentBean;
import com.etong.citymap.bean.ImageBean;
import com.etong.citymap.bean.ProblemBean;
import com.etong.citymap.connect.HttpSendData;
import com.etong.citymap.db.util.CityApplication;
import com.etong.citymap.util.ActivityUtil;
import com.etong.citymap.util.StringUtil;
import com.etong.citymap.util.log.LogUtil;
import com.supermap.data.Point2D;

/**
 * 执法通问题处理
 */
public class LawUploadActivity extends Activity implements OnClickListener {
	Button law_but_back;
	LinearLayout law_but_button_back;
	Spinner law_type;
	Spinner law_dalei;
	Spinner law_idea;
	Spinner law_xiaolei;
	Button law_locationbut;
	EditText law_zuobiao;
	EditText law_status;
	EditText law_mustdate;
	EditText law_suggestion;
	EditText law_situation;
	LinearLayout law_appendix;
	LinearLayout law_display;
	LinearLayout law_menu;
	LinearLayout law_upload;
	TextView law_display_count;
	RelativeLayout law_display_count_bg;
	LinearLayout law_bgid;
	LinearLayout lawmmenu_tb;
	LinearLayout lawmmenu_yq;
	LinearLayout lawmmenu_zx;
	private static ProblemBean[] cacheresult;
	private static String[] law_typestrings;
	private static String[] law_daleistrings;
	private static String[] law_xiaoleistrings;
	private static String[] law_lawideastrings;
	private ArrayAdapter<String> law_typeadapter;
	private ArrayAdapter<String> law_daleiadapter;
	private ArrayAdapter<String> law_xiaoleiadapter;
	private ArrayAdapter<String> law_lawideaadapter;

	private CityApplication cityApplication;
	boolean isshow = false;
	int Rrsultcode = 100;
	AlertDialog load;
	AlertDialog uploadalert;
	PopupWindow popupWindow;
	AssignmentBean bean;
	private Point2D locationPoint;
	String yijian = "";
	private int typepostion;
	Handler handler = new Handler(new Handler.Callback() {
		@Override
		public boolean handleMessage(Message msg) {
			if (msg.what == 2) {
				load.dismiss();
				law_typeadapter = new ArrayAdapter<String>(
						LawUploadActivity.this, R.layout.myspinner,
						law_typestrings);
				law_typeadapter
						.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
				law_type.setAdapter(law_typeadapter);
				law_daleiadapter = new ArrayAdapter<String>(
						LawUploadActivity.this, R.layout.myspinner,
						law_daleistrings);
				law_daleiadapter
						.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
				law_dalei.setAdapter(law_daleiadapter);
				law_xiaoleiadapter = new ArrayAdapter<String>(
						LawUploadActivity.this, R.layout.myspinner,
						law_xiaoleistrings);
				law_xiaoleiadapter
						.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
				law_xiaolei.setAdapter(law_xiaoleiadapter);
				
				law_lawideastrings = new String[1];
				law_lawideastrings[0] = "已处理";
				law_lawideaadapter = new ArrayAdapter<String>(LawUploadActivity.this, R.layout.myspinner,law_lawideastrings);
				law_idea.setAdapter(law_lawideaadapter);
				
				bean = (AssignmentBean) LawUploadActivity.this.getIntent()
						.getSerializableExtra("bean");
				if (bean != null) {
					law_type.setEnabled(false);
					law_dalei.setEnabled(false);
					law_xiaolei.setEnabled(false);
					law_status.setEnabled(false);
					law_mustdate.setEnabled(false);
					law_situation.setText(bean.getSituation());
					law_mustdate.setText(bean.getTheoryenddate());
					law_status.setText(bean.getStatusname());
					locationPoint = new Point2D();
					locationPoint.setX(Double.valueOf(bean.getX()));
					locationPoint.setY(Double.valueOf(bean.getY()));
					String text = "精度:" + locationPoint.getX() + " 纬度"
							+ locationPoint.getY();
					law_zuobiao.setText(text);
					for (int i = 0; i < cacheresult.length; i++) {
						if (cacheresult[i].getId() == Integer.valueOf(bean
								.getType())) {
							gettype(i);
							law_type.setSelection(i);
							ProblemBean[] dalei = cacheresult[i].getChild();
							for (int t = 0; t < dalei.length; t++) {
								if (dalei[t].getId() == Integer.valueOf(bean
										.getBigclass())) {
									getdalei(t);
									law_dalei.setSelection(t);
									ProblemBean[] xiaolei = dalei[t].getChild();
									for (int y = 0; y < xiaolei.length; y++) {
										if (xiaolei[y].getId() == Integer
												.valueOf(bean.getSmallclass())) {
											law_xiaolei.setSelection(y);
											break;
										}
									}
									break;
								}
							}
							break;
						}
					}

				}
			} else if (msg.what == 5) {// 数据上传和保存
				if (msg.arg1 == 6) {
					uploadalert.dismiss();
					Toast.makeText(LawUploadActivity.this, "上传完毕",
							Toast.LENGTH_SHORT).show();
					finish();
				} else {
					String data = msg.getData().getString("msg");
					uploadalert.setMessage(data);
				}

			} else if (msg.what == 6) {
				uploadalert.dismiss();
				Toast.makeText(LawUploadActivity.this, msg.obj.toString(),
						Toast.LENGTH_SHORT).show();
			}
			return false;
		}
	});

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.lawupload);
		cityApplication = (CityApplication)getApplication();
		init();
		load = new ProgressDialog(this);
		load.setTitle(null);
		load.setMessage("请稍等,正在加载数据...");
		load.show();
		uploadalert = new ProgressDialog(this);
		uploadalert.setTitle(null);
		new Loading();
		View view = LayoutInflater.from(this).inflate(R.layout.lawmenu, null);
		popupWindow = new PopupWindow(view);
		popupWindow.setAnimationStyle(R.style.popwin_anim_style);
		popupWindow.setWidth(LayoutParams.WRAP_CONTENT);
		popupWindow.setHeight(LayoutParams.WRAP_CONTENT);
		lawmmenu_tb = (LinearLayout) view.findViewById(R.id.lawmmenu_tb);
		lawmmenu_yq = (LinearLayout) view.findViewById(R.id.lawmmenu_yq);
		lawmmenu_zx = (LinearLayout) view.findViewById(R.id.lawmmenu_zx);
		lawmmenu_tb.setOnClickListener(this);
		lawmmenu_yq.setOnClickListener(this);
		lawmmenu_zx.setOnClickListener(this);
	}

	void init() {
		law_but_back = (Button) findViewById(R.id.law_but_back);
		law_but_back.setOnClickListener(this);
		law_type = (Spinner) findViewById(R.id.law_type);
		law_dalei = (Spinner) findViewById(R.id.law_dalei);
		law_xiaolei = (Spinner) findViewById(R.id.law_xiaolei);
		law_idea = (Spinner) findViewById(R.id.law_idea);
		law_locationbut = (Button) findViewById(R.id.law_location);
		law_locationbut.setOnClickListener(this);
		law_zuobiao = (EditText) findViewById(R.id.law_zuobiao);
		law_status = (EditText) findViewById(R.id.law_status);
		law_mustdate = (EditText) findViewById(R.id.law_mustdate);
		law_suggestion = (EditText) findViewById(R.id.law_suggestion);
		law_appendix = (LinearLayout) findViewById(R.id.law_appendix);
		law_appendix.setOnClickListener(this);
		law_display = (LinearLayout) findViewById(R.id.law_display);
		law_display.setOnClickListener(this);
		law_display_count = (TextView) findViewById(R.id.law_display_count);
		law_display_count_bg = (RelativeLayout) findViewById(R.id.law_display_count_bg);
		law_menu = (LinearLayout) findViewById(R.id.law_menu);
		law_menu.setOnClickListener(this);
		law_upload = (LinearLayout) findViewById(R.id.law_upload);
		law_upload.setOnClickListener(this);
		law_situation = (EditText) findViewById(R.id.law_situation);
		law_bgid = (LinearLayout) findViewById(R.id.law_bgid);
		law_bgid.setOnClickListener(this);
	}

	@Override
	protected void onResume() {
		if(cityApplication.isReturnResult()){
			locationPoint = cityApplication.getLocPoint();
		}
		cityApplication.setReturnResult(false);
		ImageBean[] ils = cityApplication.getImageList();
		ImageBean[] ilns = cityApplication.getImageList_Net();
		if ( ils != null || ilns != null) {
			int count = 0;
			law_display.setVisibility(LinearLayout.VISIBLE);
			if (ils != null) {
				for (int i = 0; i < ils.length; i++) {
					if (ils[i].isIsSelect()) {
						++count;
					}
				}
			}
			if (ilns != null) {
				if (ilns != null) {
					for (int i = 0; i < ilns.length; i++) {
						if (ilns[i].isIsSelect()) {
							++count;
						}
					}
				}

			}
			if (count > 0) {
				law_display_count_bg.setVisibility(LinearLayout.VISIBLE);
				law_display_count.setText(count + "");
			} else {
				law_display_count_bg.setVisibility(LinearLayout.GONE);
				law_display_count.setText("");
			}
		}

		super.onResume();
	}

	class Loading extends Thread {
		public Loading() {
			start();
		}

		@Override
		public void run() {
			if (cacheresult == null) {
				String url = "supervisor/ashx/gettype.ashx"; // 001 001
				Map<String, String> map = new HashMap<String, String>();
				map.put("superid", cityApplication.getZFTUserId());
				map.put("code", cityApplication.getZFTOrgId());
				try {
					String result = HttpSendData.SendGet(url, map, "utf-8",cityApplication.getHTTPURL());
					JSONArray jsonArray = new JSONArray(result);
					cacheresult = new ProblemBean[jsonArray.length()];
					law_typestrings = new String[jsonArray.length()];
					for (int i = 0; i < jsonArray.length(); i++) {
						JSONObject jsonObject = jsonArray.getJSONObject(i);
						cacheresult[i] = new ProblemBean();
						cacheresult[i].setName(jsonObject.getString("name"));
						cacheresult[i].setId(jsonObject.getInt("id"));
						law_typestrings[i] = cacheresult[i].getName();
						String child = jsonObject.getString("child");
						if (StringUtil.IsNotNull(child)) {
							cacheresult[i].setChild(getChild(child));
						}
					}
					ProblemBean[] cachedale = cacheresult[0].getChild();
					law_daleistrings = new String[cachedale.length];
					for (int i = 0; i < cachedale.length; i++) {
						law_daleistrings[i] = cachedale[i].getName();
					}
					ProblemBean[] cachexiaolei = cachedale[0].getChild();
					law_xiaoleistrings = new String[cachexiaolei.length];
					for (int i = 0; i < cachexiaolei.length; i++) {
						law_xiaoleistrings[i] = cachexiaolei[i].getName();
					}

				} catch (Exception e) {
					LogUtil.e(e);
				}
			}
			Message message = new Message();
			message.what = 2;
			handler.sendMessage(message);
		}

		private ProblemBean[] getChild(String json) throws Exception {
			JSONArray jsonArray = new JSONArray(json);
			ProblemBean[] beans = new ProblemBean[jsonArray.length()];
			for (int i = 0; i < jsonArray.length(); i++) {
				JSONObject jsonObject = jsonArray.getJSONObject(i);
				beans[i] = new ProblemBean();
				beans[i].setName(jsonObject.getString("name"));
				beans[i].setId(jsonObject.getInt("id"));
				try {
					String child = jsonObject.getString("child");
					if (StringUtil.IsNotNull(child)) {
						beans[i].setChild(getChild(child));
					}
				} catch (Exception e) {
				}
			}
			return beans;
		}

	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == requestCode) {
			finish();
		}

	}

	@Override
	public void onClick(View v) {
		ImageBean[] ils = cityApplication.getImageList();
		if (v == law_but_back) {
			finish();
		}
		if (law_appendix == v) {
			ActivityUtil.ToActivity(this, CameraActivity.class);
		}
		if (law_display == v) {
			Intent intent = new Intent(this, CamerDisplayActivity.class);
			if (ils != null) {
				ArrayList<String> camernames = new ArrayList<String>();
				for (int i = 0; i < ils.length; i++) {
					if (ils[i].isIsSelect()) {
						camernames.add(ils[i].getPathname());
					}
				}
				intent.putStringArrayListExtra("list", camernames);
			}
			intent.putExtra("pro", true);
			startActivity(intent);
		}
		if (law_menu == v) {
			if (!isshow) {
				int[] location = new int[2];
				v.getLocationOnScreen(location);
				int jianq = 243;
				popupWindow.showAtLocation(v, Gravity.NO_GRAVITY, location[0],
						location[1] - jianq);
				isshow = true;
			} else {
				popupWindow.dismiss();
				isshow = false;
			}

		}
		if (law_bgid == v) {
			popupWindow.dismiss();
		}
		if (law_upload == v) {
			if (ils == null) {
				Toast.makeText(this, "请先拍照", Toast.LENGTH_SHORT).show();
			} else {
				yijian = law_suggestion.getText().toString();
				uploadalert.show();
				new UploadData();

			}
		}

		if (lawmmenu_tb == v) {
			Intent intent = new Intent(this, LawTBActivity.class);
			intent.putExtra("bean", bean);
			startActivityForResult(intent, Rrsultcode);
		}
		if (lawmmenu_yq == v) {
			Intent intent = new Intent(this, LawYQActivity.class);
			intent.putExtra("bean", bean);
			startActivityForResult(intent, Rrsultcode);
		}
		if (lawmmenu_zx == v) {
			Intent intent = new Intent(this, LawZXActivity.class);
			intent.putExtra("bean", bean);
			startActivityForResult(intent, Rrsultcode);
		}
		if (law_locationbut == v) {
			/*Bundle bundle = new Bundle();
			if (locationPoint != null) {
				bundle.putDouble("x", locationPoint.getX());
				bundle.putDouble("y", locationPoint.getY());
			}*/
			cityApplication.setPrePoint(locationPoint);
			ActivityUtil.ToActivity(LawUploadActivity.this,	MapActivity.class);
		}
	}

	public void gettype(int position) { // 设置类型下的大类

		typepostion = position;
		ProblemBean[] beans = cacheresult[position].getChild();
		law_daleistrings = new String[beans.length];
		for (int i = 0; i < beans.length; i++) {
			law_daleistrings[i] = beans[i].getName();
		}
		law_daleiadapter = new ArrayAdapter<String>(LawUploadActivity.this,
				R.layout.myspinner, law_daleistrings);
		law_daleiadapter
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		law_dalei.setAdapter(law_daleiadapter);
		ProblemBean[] cachexiaolei = beans[0].getChild();
		law_xiaoleistrings = new String[cachexiaolei.length];
		for (int i = 0; i < cachexiaolei.length; i++) {
			law_xiaoleistrings[i] = cachexiaolei[i].getName();
		}
		law_xiaoleiadapter = new ArrayAdapter<String>(LawUploadActivity.this,
				R.layout.myspinner, law_xiaoleistrings);
		law_xiaoleiadapter
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		law_xiaolei.setAdapter(law_xiaoleiadapter);

	}

	public void getdalei(int position) { // 设置大类下的小类
		ProblemBean[] beans = cacheresult[typepostion].getChild();
		ProblemBean[] cachexiaolei = beans[position].getChild();
		law_xiaoleistrings = new String[cachexiaolei.length];
		for (int i = 0; i < cachexiaolei.length; i++) {
			law_xiaoleistrings[i] = cachexiaolei[i].getName();
		}
		law_xiaoleiadapter = new ArrayAdapter<String>(LawUploadActivity.this,
				R.layout.myspinner, law_xiaoleistrings);
		law_xiaoleiadapter
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		law_xiaolei.setAdapter(law_xiaoleiadapter);

	}

	class UploadData extends Thread {// hws
		public UploadData() {
			start();
		}

		@Override
		public void run() {
			String Fjname = "";
			ImageBean[] ils = cityApplication.getImageList();
			if (ils != null) {
				for (int i = 0; i < ils.length; i++) {
					if (ils[i].isIsSelect()) {
						Fjname += ils[i].getPathname() + ",";
					}
				}
			}

			Message message = new Message();
			message.what = 5;
			message.getData().putString("msg", "正在上传数据");
			handler.sendMessage(message);
			String url = "supervisor/ashx/cztrans.ashx";
			Map<String, String> map = new HashMap<String, String>();
			map.put("Prjid", bean.getPrjid());
			String cache = Fjname.substring(0, Fjname.length() - 1);
			map.put("Fjname", cache);
			map.put("Superid", cityApplication.getZFTUserId()+ "");
			map.put("Code", cityApplication.getZFTOrgId()+ "");
			try {
				String result = HttpSendData.SendGet(url, map, "utf-8",cityApplication.getHTTPURL());
				if (StringUtil.IsNull(result)) {
					message = new Message();
					message.obj = "连接服务器出错";
					message.what = 6;
					handler.sendMessage(message);
				} else {
					switch (Integer.valueOf(result)) {
					case -3: {
						message = new Message();
						message.obj = "服务器出错";
						message.what = 6;
						handler.sendMessage(message);
						break;
					}
					case -1: {
						message = new Message();
						message.what = 6;
						message.obj = "服务器出错";
						handler.sendMessage(message);
						break;
					}
					case -4: {
						message = new Message();
						message.obj = "已在其他机器登录";
						message.what = 6;
						handler.sendMessage(message);
						break;
					}
					case -2: {
						message = new Message();
						message.what = 6;
						message.obj = "上报坐标不在所管辖的范围内";
						handler.sendMessage(message);
						break;
					}
					default: {
						message = new Message();
						message.what = 5;
						message.getData().putString("msg", "数据上传成功,正在上传附件");

						handler.sendMessage(message);
						if (StringUtil.IsNull(result)) {
							message = new Message();
							message.obj = "连接网络出错";
							message.what = 6;
							handler.sendMessage(message);
						} else {
							int prjid = Integer.valueOf(result);
							if (ils != null) {
								String urlimage = "supervisor/ashx/czfileup.ashx";
								for (int i = 0; i < ils.length; i++) {
									String path = Environment
											.getExternalStorageDirectory()
											+ cityApplication.CameraPath;
									if (ils[i].isIsSelect()) {
										Map<String, String> params = new HashMap<String, String>();
										String imagename = ils[i]
												.getPathname();
										params.put("Actinsid",
												bean.getActinsid());
										params.put("Prjid", bean.getPrjid());
										params.put("status", "2");
										params.put("insid", bean.getInsid());
										params.put("wfid", bean.getWfid());
										params.put("assignid",
												bean.getAssignid());
										params.put("idea", law_idea.getSelectedItem().toString());
										params.put("decision", yijian);
										params.put("ls_name", imagename);
										params.put("userid",cityApplication.getZFTUserId());
										String jg = HttpSendData
												.SendTextAndFile(urlimage,
														params, path + "/"
																+ imagename,cityApplication.getHTTPURL());
										if (StringUtil.IsNull(jg)) {
											message = new Message();
											message.obj = "连接服务器出错";
											message.what = 6;
											handler.sendMessage(message);
										} else {
											switch (Integer.valueOf(jg)) {
											case -1: {
												message = new Message();
												message.obj = "服务器出错";
												message.what = 6;
												handler.sendMessage(message);
												break;
											}
											case -2: {
												message = new Message();
												message.obj = "服务器出错";
												message.what = 6;
												handler.sendMessage(message);
												break;
											}
											case -3: {
												message = new Message();
												message.obj = "服务器出错";
												message.what = 6;
												handler.sendMessage(message);
												break;
											}
											case -4: {
												message = new Message();
												message.obj = "已在其他机器登录";
												message.what = 6;
												handler.sendMessage(message);
												break;
											}
											default: {
												message = new Message();
												message.what = 5;
												message.getData().putString(
														"msg",
														"附件" + (i + 1)
																+ ",上传成功");
												handler.sendMessage(message);
												break;
											}
											}

										}
									}
								}
							}
						}

						message = new Message();
						message.what = 5;
						message.arg1 = 6;
						handler.sendMessage(message);
						break;
					}
					}
				}

			} catch (Exception e) {
				LogUtil.e(e);
			}

		}
	}

}
